package com.wxx.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

public class SocketClient {
    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("请输入IP,端口,连接数");
            return;
        }
        int count = Integer.parseInt(args[2]);
        if (count <= 0) {
            System.out.println("连接数最少为1");
            return;
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup());
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel channel) throws Exception {
                ChannelPipeline pipeline = channel.pipeline();
                pipeline.addLast(new StringDecoder(Charset.forName("GBK")));
                pipeline.addLast(new StringEncoder(Charset.forName("GBK")));
            }
        });

        for (int i = 0; i < count; i++) {
            bootstrap.connect(args[0], Integer.parseInt(args[1])).addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess()) {
                    System.out.println("链接服务器成功>>>" + channelFuture.channel());
                } else {
                    System.out.println("链接服务器失败>>>" + channelFuture.cause().getMessage());
                }
            });
        }
    }
}
